const express = require('express')
const router = express.Router()
const fs = require('fs')
const multer = require('multer')

//导入数据库 sqlFn('sql',[],res=>{})
const sqlFn = require('../mysql')


// //图片需要的模块
// const multer = require('multer')
// const fs = require('fs')

// const jwt=require('jsonwebtoken')
// // config.jwtSecert
// const config = require('./secert')




/**
 * 商品列表：获取分页 {total:'',arr:[{},{},{}],pagesize:8,}
 * 参数：page 页码
 */
router.get('/hello', (req, res) => {
    res.send("HELLO")
    // const page = req.query.page || 1;
    // const sqlLen = "select * from project where id";
    // sqlFn(sqlLen, null, data => {
    //     let len = data.length;
    //     const sql = "select * from project order by id desc limit 8 offset " + (page - 1) * 8;
    //     sqlFn(sql, null, result => {
    //         if (result.length > 0) {
    //             res.send({
    //                 status: 200,
    //                 data: result,
    //                 pageSize: 8,
    //                 total: len
    //             })
    //         } else {
    //             res.send({
    //                 status: 500,
    //                 msg: "暂无数据"
    //             })
    //         }
    //     })
    // })
})

router.get('/getGoods', (req, res) => {
    const sqlLen = "select * from goods";
    sqlFn(sqlLen, null, data => {
        let len = data.length;
        if (len > 0) {
            res.send({
                status: 200,
                data: data
            })
        } else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})


// router.get('/getCategory', (req, res) => {
//     const sqlLen = "select * from category";
//     sqlFn(sqlLen, null, data => {
//         let len = data.length;
//         if (len > 0) {
//             res.send({
//                 status: 200,
//                 data: data
//             })
//         } else {
//             res.send({
//                 status: 500,
//                 msg: "暂无数据"
//             })
//         }
//     })
// })
/**
 * 商品查询接口 search
 * 参数：search  {search:xx}
 */
router.get("/goods_search", (req, res) => {
    console.log('query:', req.query)
    console.log('传过来的参数:', req.query.search_word)
    var search = req.query.search_word;
    const sql = "select * from goods where concat(`name`,`category`,`SellingPoint`,`description`) like '%" + search + "%'";
    sqlFn(sql, null, (result) => {
        console.log('result:', result)
        console.log('result长度:', result.length)
        if (result.length > 0) {
            console.log("我在这")
            res.send({
                status: 200,
                result: result
            })
        } else {
            res.send({
                status: 500,
                result:result,
                msg: "暂无数据"
            })
        }
    })
})




/**
 * 上传图片 post请求 upload
 * 说明：
 *  1.后台安装 multer 模块   同时引入fs模块
 *  2.router.js入口文件导入模块
 *      const fs=require('fs')
        const multer=require('multer')
 *  3.上传图片 
 * 
 */

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./server/upload/")
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname)
    }
})

var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}

var uploadFolder = './server/upload/';
createFolder(uploadFolder);
var upload = multer({
    storage: storage
});

/**
 * 图片上传 post请求
 */
router.post('/upload', upload.single('file'), function (req, res, next) {
    var file = req.file;
    console.log('file:',file.path)
    let f_address = "http://localhost:8989" + file.path.replace("server\\upload\\", "/")
    console.log('文件类型：%s', file.mimetype);
    console.log('原始文件名：%s', file.originalname);
    console.log('文件大小：%s', file.size);
    console.log('文件保存路径：%s', file.path);
    console.log("文件访问地址：%s", f_address)
    // res.json({
    //     res_code: '0',
    //     name: file.originalname,
    //     url: file.path
    // });
    res.send({
        res_code: '0',
        name: file.originalname,
        url: f_address
    });
});

router.post('/goods_submit', (req, res) => {
    console.log('req:', req.query);
    const sql = "insert into goods(name,price,number,category,photo,SellingPoint,description) values(?,?,?,?,?,?,?)";
    let arr = [req.query.name, req.query.price, Number(req.query.num), req.query.category, req.query.image, req.query.sellPoint, req.query.desc]
    sqlFn(sql, arr, (result) => {
        console.log('result:', result)
        res.send({
            res_code: '发送成功',
        });
    })
});


router.post('/goods_editor', (req, res) => {
    console.log('req:', req.query);
    const sql = "update goods set name=?,price=?,number=?,category=?,photo=?,SellingPoint=?,description=? where id=?";
    let arr = [req.query.name, req.query.price, Number(req.query.num), req.query.category, req.query.image, req.query.sellPoint, req.query.desc, Number(req.query.id)]
    sqlFn(sql, arr, (result) => {
        console.log('result:', result)
        res.send({
            res_code: '修改成功',
        });
    })
});

router.post('/goods_delete', (req, res) => {
    console.log('req:', req.query);
    const sql = "delete from goods where id=?";
    let arr = [Number(req.query.goods_id)]
    sqlFn(sql, arr, (result) => {
        console.log('result:', result)
        res.send({
            res_code: '删除成功',
        });
    })
});
router.post('/goods_deleteSelect', (req, res) => {
    console.log(req.query.data)
    let data = JSON.parse(req.query.data);
    const sql = "delete from goods where id=?";

    data.forEach(el => {
        let goods_id = [Number(el.id)]
        sqlFn(sql, goods_id, (result) => {
            console.log('result:', result)
        })
    });
    res.send({
        res_code: '删除成功',
    });
});

module.exports = router